import json
import time

from django_redis import get_redis_connection

'''
1. 安装django-redis
pip install django-redis

2. django 项目目录下 settings.py里添加以下配置，

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://:123456@8.134.38.151:6379/0",  # 存入db0
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "db2": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://:123456@8.134.38.151:6379/2",  # 存入db2
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
}

redis 配置
host:8.134.38.151
port:6379
auth:123456
'''


def redis_set_val():
    conn = get_redis_connection()  # 使用默认配置
    conn2 = get_redis_connection('db2')  # 存入db 2

    test_data = {
        'ts': int(time.time()),
        'msg': 'test'
    }
    conn.set('str', json.dumps(test_data))  # 设置字符串
    conn.hset('hash', 'key1', 'val1')  # 设置hash
    conn.hmset('hash', {'key2': 'val2', 'key3': 'val3'})

    conn.lpush('list', 1)
    conn.lpush('list', 2)
    conn.lpush('list', 3)

    # 获取缓存
    print(conn.get('str'))
    print(conn.hget('hash', 'key1'))
    print(conn.hget('hash', 'key2'))
    print(conn.lrange('list', 0, 2))

    conn2.set('foo', 'bar')
    print(conn2.get('foo'))
